package springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 咕唧
 * @Date 2022/6/28 10:40
 * @Version 1.0
 * 前置过滤器
 */
@Component
public class MyPreFilter1 extends ZuulFilter {
    /**
     * 过滤器的类型
     *
     * @return
     */
    @Override
    public String filterType() {
        //声明为前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器的优先级，数字越小，优先级越高，
     * spring 存在默认过滤器，所有自己设置的过滤器数字最好大于5
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 100;
    }

    /**
     * 是否开启当前过滤器 true开启，false关闭
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //根据业务和前面的过滤器 判断是否需要开启这个过滤器
        RequestContext currentContext = RequestContext.getCurrentContext();
        return currentContext.sendZuulResponse();
//        return true;
    }

    /**
     * 当前过滤器需要执行的操作
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("MyPreFilter1的run方法执行了");
        //获取当前的上线文,以线程为区分,内部是threadlocal
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取请求相关
        HttpServletRequest request = currentContext.getRequest();
        //获取相应相关
        HttpServletResponse response = currentContext.getResponse();
        //设置相应头
//        currentContext.addZuulResponseHeader("content-Type", "text/html;charset=utf-8");
//        response.addHeader("content-Type", "text/html;charset=utf-8");
//        try {
//            response.getWriter().write("这是response返回的数据");
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        //存放数据
        currentContext.set("username", "张三");
        //拦截请求
//        currentContext.setSendZuulResponse(false);


        return null;
    }
}
